package util

import (
	"bytes"
	"fmt"
	"os/exec"
	"path/filepath"

	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

func Run(cmd *exec.Cmd, debug ...bool) (string, string, error) {
	var stdout bytes.Buffer
	cmd.Stdout = &stdout
	var stderr bytes.Buffer
	cmd.Stderr = &stderr
	err := cmd.Start()
	if err != nil {
		return "", "", errors.Wrap(err, "in start command")
	} else {
		state, err := cmd.Process.Wait()
		if err == nil {
			var stderrOutput = stderr.String()
			var stdoutOutput = stdout.String()
			if len(debug) > 0 && debug[0] {
				logrus.Info("cmd is", cmd.String())
				logrus.Info("cmd output is", stdoutOutput)
				logrus.Info("cmd erput is", stderrOutput)
			}
			if !state.Success() {
				return "", "", fmt.Errorf("[Exit:%d]%s", state.ExitCode(), stderrOutput)
			} else {
				return stdoutOutput, stderrOutput, nil
			}
		} else {
			return "", "", errors.Wrap(err, "in command execution")
		}
	}
}

func UseOrg(cmd *exec.Cmd, base string, org *Organization, needConnToOrderer bool) *exec.Cmd {

	if org == nil {
		//使用随机
		org = Config.GetPeerOrganization()
		logrus.Errorln("使用机构：" + org.Msp)
	}

	cfgDir := filepath.Join(base, "config")

	p, _ := org.GetLocalPeer(true)

	envs := []string{
		"FABRIC_CFG_PATH=" + cfgDir,
		"CORE_PEER_TLS_ENABLED=true",
		"CORE_PEER_LOCALMSPID=" + org.Msp,
		"CORE_PEER_TLS_ROOTCERT_FILE=" + p.GetTlsCaPath(base),
		"CORE_PEER_MSPCONFIGPATH=" + org.GetMspPath(base),
		"CORE_PEER_ADDRESS=" + p.GetUrl(),
	}
	cmd.Env = append(cmd.Env, envs...)
	if needConnToOrderer {
		cmd.Args = append(cmd.Args, Config.GetOrdererOrganization().GetConnArgs(base)...)
	}
	return cmd
}
